package org.example.cloud.controller;

import org.example.cloud.bean.User;
import org.example.cloud.result.Result;
import org.example.cloud.service.implementation.FileFolderService;
import org.example.cloud.service.implementation.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;


@Controller
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private FileFolderService fileFolderService;
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    @CrossOrigin
    @PostMapping("/api/login")
    @ResponseBody
    public Result login(@RequestBody User requestUser) {
        // 1. 参数基础校验
        if (requestUser == null) {
            logger.error("请求参数不能为空");
            return Result.error(400, "请求参数不能为空");
        }

        // 2. 获取并验证用户名
        String username = requestUser.getUsername();
        if (username == null || username.trim().isEmpty()) {
            logger.error("用户名不能为空");
            return Result.error(400, "用户名不能为空");
        }

        // 3. 获取并验证密码
        String password = requestUser.getPassword();
        if (password == null || password.trim().isEmpty()) {
            logger.error("密码不能为空");
            return Result.error(400, "密码不能为空");
        }

        try {
            // 4. XSS防护处理
            username = HtmlUtils.htmlEscape(username.trim());
            logger.debug("接收到的用户名: {}, 密码: {}", username, password);
            // 5. 安全比较（避免时序攻击）
            User user = userService.getUserByUsername(username);
            if (user == null) {
                logger.debug("用户不存在: {}", username);
                return Result.error(400, "用户不存在，请先注册");
            }
            boolean isAuthenticated =
                    slowEquals(username, user.getUsername()) &&
                            slowEquals(password, user.getPassword());

            logger.debug("数据库中用户名: {}, 密码: {}", user.getUsername(),user.getPassword());
            // 6. 返回结果
            if (isAuthenticated) {
                logger.info("登录成功");
                fileFolderService.initFolder(username);
                return new Result(200, "登录成功",user);
            } else {
                // 生产环境建议记录到日志系统而非控制台
                return Result.error(400, "用户名或密码错误");
            }
        } catch (Exception e) {
            // 7. 异常处理
            logger.error("系统处理登录请求时发生错误", e);
            return Result.error(500, "系统处理登录请求时发生错误");
        }
    }

    /**
     * 安全字符串比较（防止时序攻击）
     */
    private boolean slowEquals(String a, String b) {
        if (a == null || b == null) {
            return false;
        }
        int diff = a.length() ^ b.length();
        for (int i = 0; i < a.length() && i < b.length(); i++) {
            diff |= a.charAt(i) ^ b.charAt(i);
        }
        return diff == 0;
    }
}
